<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\captcha\Captcha;
use think\facade\Session;
use think\facade\Config;

class Base extends Controller
{   

	public $base_data;

	/*页面必须继承 接口无需继承*/
    public function __construct(){
        parent::__construct();
        header('Access-Control-Allow-Origin:*');
        $this->check_load();
        //防止网站ip被收录 以ip形式访问网站 直接跳转至域名形式
	    if($_SERVER['HTTP_HOST']==Config::get('app.web_ip')){
		    header("Location:https://".Config::get('app.web_host_name').$_SERVER['REQUEST_URI']);
		    exit;
	    }
	    $class_data=[];
        $first_class=Db::table('lily_classify')->field('cname,id,route_name,route_id,alias_name')->where([['status','=',1],['fid','=',0],['is_show','=',1]])->order('seq','asc')->select();/*导航*/
        foreach ($first_class as $key => $value) {
        	if(!empty($value['route_name'])){
        		$first_url=$value['route_name'];
        	}else{
                $first_url=change_lower_symbol($value['cname']);
        	}
        	$value['url']=$first_url;
            $class_data[$key]['first']=$value;

        	$second=Db::table('lily_classify')->field('cname,id,route_name,route_id,alias_name')->where([['status','=',1],['fid','=',$value['id']],['is_show','=',1]])->order('seq','asc')->select();
        	if(!empty($second)){
        		foreach ($second as $k => $v) {
        			if(!empty($v['route_name'])){
		        		$second_url=$first_url."/".$v['route_name'];
		        	}else{
		                $second_url=$first_url."/".change_lower_symbol($v['cname']);
		        	}
		        	$second[$k]['url']=$second_url;
        		}
        		$class_data[$key]['second']=$second;
        	}
        }
        $this->base_data['nav_class']=$class_data;/*导航*/
       // dump($class_data);exit;
        $this->base_data['current_url']=http_type().$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];/*页面url*/
        $this->base_data['no_parameter_url']=http_type().$_SERVER['HTTP_HOST'].explode('?', $_SERVER['REQUEST_URI'])[0];/*当前页面无参数链接*/
        $this->base_data['move_ad_parameter_url']=del_gclid($this->base_data['current_url']);/*移除广告参数后的链接*/

        $this->base_data['ip']=$this->get_ip();/*ip*/
        $this->base_data['send_num']=$this->get_day_ip_send_num();/*当天发送询盘次数*/
        if(Config::get('app.v_code_num')>=$this->base_data['send_num']){
           $this->base_data['is_show_code']=false;/*是否显示验证码*/
        }else{
           $this->base_data['is_show_code']=true;/*是否显示验证码*/
        }
        $this->base_data['is_no_index']=$this->no_index();/*是否允许收录*/
        $this->base_data['canonical_url']=$this->canonical();/*canonical*/
        $this->base_data['iszhong']=1;
        $this->url_conme();

        $ip_t=request()->ip();
		if($ip_t=='154.208.250.30'||$ip_t=='114.215.175.126'){
			echo "1";exit;
		}
        /*if($ip_t!=''){
        	$ip_t_data=Db::table('ips')->field('id,num')->where('ip','=',$ip_t)->find();
        	if(empty($ip_t_data)){
        		$sql="insert into ips (`ip`,`num`) values ('".$ip_t."',1)";
        	}else{
        		$num=$ip_t_data['num']+1;
        		$sql="update ips set `num`=".$num.",t=concat(t,'".$this->base_data['current_url'].",') where id=".$ip_t_data['id'];
        	}
        	Db::query($sql);
        }
*/
    }
    
    /*获取ip*/
   /* public function get_ip1(){
        $ip = $_SERVER['REMOTE_ADDR'];
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
		    foreach ($matches[0] AS $xip) {
			    if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
			    	$ip = $xip;
			    	break;
			    }
		    }
		}elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
			$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
		} elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
			$ip = $_SERVER['HTTP_X_REAL_IP'];
		}
		return $ip;
    }*/
    /*获取ip*/
    public function get_ip(){
		\think\Container::get('log')->record($_SERVER, '测试IP开始('. request()->ip() .'):');
        $ip=FALSE;
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $ip=$_SERVER["HTTP_CLIENT_IP"];
        }
        if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
            for ($i = 0; $i < count($ips); $i++) {
            	/*if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
            		$ip = $ips[$i];
            		break;
            	}*/
            	if (!preg_match("(10│172.16│192.168)", $ips[$i])) {
            		$ip = $ips[$i];
            		break;
            	}
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }
    
    /*获取当天发送询盘次数，超过指定次数 需要输入验证码*/
    public function get_day_ip_send_num(){
    	$start=date("Y-m-d 00:00:00",time());
	    $end=date("Y-m-d H:i:s",time());
	    $cishu=Db::connect('publicdata')->table('lily_enquire')->where([['status','=',1],['create_time','>=',$start],['create_time','<=',$end],['ip','=',$this->base_data['ip']]])->count('id');
	    return $cishu;
    }
    
    /*noindex标签控制 noinde设置页面是否允许收录*/
    /*列表页筛选存在筛选的禁止收录*/
    public function no_index(){
	    $parsed = parse_url($this->base_data['current_url']);
	    if(isset($parsed['query'])){
	        parse_str($parsed['query'], $params);
	        unset($params['gclid']);
	        if(count($params)>=1){
	            return true;
	        }else{
	        	return false;
	        }
	    }else{
	    	return false;
	    }
    }
    
    /*canonical标签控制 转移url权重 用于重复页面*/
    public function canonical(){

    	if(isset(request()->param()['class_id'])){
    		$canonical=Db::table('lily_classify_canonical')->where([['status','=',1],['c_class_id','=',request()->param()['class_id']]])->find();
    		if(empty($canonical)){
	    		$broken = parse_url($_SERVER['REQUEST_URI']);
			    $path = $broken['path']; 
			    if(stripos($path, '/page/')!==false){
			        $pos = stripos($path, '/page/'); 
			        $path = substr($path, 0, $pos+1);
			    }
			    return "https://".Config::get('app.web_host_name').$path;
	    	}else{
	            $str=get_class_uplower_url($canonical['master_class_id']);
	            return "https://".Config::get('app.web_host_name').'/'.$str;
	    	}
    	}else{
    		$broken = parse_url($_SERVER['REQUEST_URI']);
		    $path = $broken['path']; 
		    if(stripos($path, '/page/')!==false){
		        $pos = stripos($path, '/page/'); 
		        $path = substr($path, 0, $pos+1);
		    }
		    return "https://".Config::get('app.web_host_name').$path;
    	}
	    
    }
    
    /*路由检测，检测classify分类是否做了变化，重新生成路由*/
    public function check_load(){
    	$filename='run';
        $monitor=Db::table('lily_classify_monitor')->where('id','=',1)->find();
        if($monitor['status']==1){
        	$str="<?php\n";
        	$str.="use think\Controller;\n";
           
            $class_data=Db::table('lily_classify')->field('id,route_id')->where([['status','=',1],['route_id','<>',0],['is_tag','<>',1]])->select();
			foreach ($class_data as $key => $value) {
			    $total=class_uplower($value['id']);
			    $class_url='';
			    for($i=count($total)-1; $i>=0 ; $i--) {
			        if($total[$i]['is_tag']!='1'){
			            if(!empty($total[$i]['route_name'])){
			                $class_url.=$total[$i]['route_name'].'/';
			            }else{
			                $class_url.=change_lower_symbol($total[$i]['cname']).'/';
			            }
			        }
			    }
			    $route_classify=Db::table('lily_route_classify')->field('mvc')->where('id','=',$value['route_id'])->find();
			    //Route::rule($class_url,$route_classify['mvc'])->append(['class_id' => $value['id']]);
			    $str.= "Route::rule('".$class_url."','".$route_classify['mvc']."')->append(['class_id' =>".$value['id']."]);\n";
			}
			$load=explode('application', __DIR__);
			if(file_exists($load[0].'route/'.$filename.'.php')){
	            unlink($load[0].'route/'.$filename.'.php');
	        }
	        $myfiletxt=fopen($load[0].'route/'.$filename.'.php', "a+");
	        fwrite($myfiletxt, $str);
	        fclose($myfiletxt);
	        Db::table('lily_classify_monitor')->where('id', 1)->update(['status' => 0]);

        }
    }
    
    /*记录url来源地址 当天单个ip只统计一次*/
    public function url_conme(){
        $ip=request()->ip();
        $this->base_data['current_url'];
        if(strpos($this->base_data['current_url'],'gclid=') !== false){ 
		    $sql="insert into lily_come (`ip`,`create_time`,`url`) value ('".$ip."','".date('Y-m-d H:i:s',time())."','".$this->base_data['current_url']."')";
	    	Db::connect('publicdata')->query($sql);
		}
    }
}
